﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace StateManager
{
    class PlayerAnimation 
    {
        public Animation Animation
        {
            get { return animation; }
        }
        Animation animation;

      
        public int FrameIndex
        {
            get { return frameIndex; }
        }
        int frameIndex;


        private float time;


        public Vector2 Origin
        {
            get { return new Vector2(Animation.FrameWidth, Animation.FrameHeight); }
        }

        public void PlayAnimation(Animation animation)
        {
            // If this animation is already running, do not restart it.
            if (Animation == animation)
                return;

            // Start the new animation.
            this.animation = animation;
            this.frameIndex = 0;
            this.time = 0.0f;
        }


        public void Draw(GameTime gameTime, SpriteBatch spriteBatch, Vector2 position, SpriteEffects spriteEffects, Color color)
        {

            Vector2 pos = position;

            pos.X += Animation.PxlOffset;
            pos.Y += Animation.PxlYOffset;
            if (Animation == null)
                throw new NotSupportedException("No animation is currently playing.");

            // Process passing time.
            time += (float)gameTime.ElapsedGameTime.TotalSeconds;
            while (time > Animation.FrameTime)
            {
                time -= Animation.FrameTime;

                // Advance the frame index; looping or clamping as appropriate.
                if (Animation.IsLooping)
                {
                    frameIndex = (frameIndex + 1) % Animation.FrameCount;
                }
                else
                {
                    frameIndex = Math.Min(frameIndex + 1, Animation.FrameCount - 1);
                }
            }

            // Calculate the source rectangle of the current frame.
            Rectangle source = new Rectangle(FrameIndex * Animation.FrameWidth, 0, Animation.FrameWidth, Animation.Texture.Height);

            // Draw the current frame.
            spriteBatch.Draw(Animation.Texture, pos, source, color, 0.0f, Vector2.Zero, 1.0f, spriteEffects, 0.0f);
        }
    }
}
